最簡單的方式就是用 in:
text = "I love cherry"
print("cherry" in text) # True
print("apple" in text) # False
find() 會回傳 子字串第一次出現的索引位置,找不到會回傳 -1
text = "hello world"
print(text.find("world")) # 6
print(text.find("apple")) # -1
count() 會計算某個字串在全文中出現的次數
text = "banana"
print(text.count("a")) # 3
print(text.count("na")) # 2
可以用 for 迴圈逐字檢查或處理字串
text = "hello"
for char in text:
print(char)
輸出:
h
e
l
l
o
article = "When he saw the monster, he screamed!"
word = "monster"
count = article.count(word)
print(f"'{word}' 出現了 {count} 次")
text = "Once upon a time"
vowels = "aeiou"
count = 0
for char in text.lower():
if char in vowels:
count += 1
print("母音數量:", count)
今天練習用 find() 精準定位字串的位置、用 count() 快速統計次數,搭配 for 迴圈更能自己寫出條件判斷的邏輯。
明天要學 try / except 例外處理,讓程式在遇到錯誤時不會直接當掉,而是能優雅地處理問題,提升程式的穩定性與可靠性!